package com.kzw.oa.action.system;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.Gson;
import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.orm.StringPropertyFilter;
import com.kzw.core.util.BeanUtil;
import com.kzw.core.util.ContextUtil;
import com.kzw.core.util.ExtjsUtil;
import com.kzw.core.web.action.BaseAction;
import com.kzw.core.web.paging.PagingBean;
import com.kzw.oa.model.system.AppUser;
import com.kzw.oa.model.system.Department;
import com.kzw.oa.model.system.UserOrg;
import com.kzw.oa.service.ext.DepartmentService2;
import com.kzw.oa.service.system.AppUserService;
import com.kzw.oa.service.system.DemensionService;
import com.kzw.oa.service.system.DepartmentService;
import com.kzw.oa.service.system.UserOrgService;
import com.kzw.oa.util.JSON;
import com.kzw.oa.util.JSON2;

public class DepartmentAction extends BaseAction {

	private Department department;

	@Resource
	private DepartmentService departmentService;
	@Resource
	private AppUserService appUserService;
	@Resource
	private DemensionService demensionService;
	@Autowired
	private DepartmentService2 deptService;
	@Autowired
	private UserOrgService userOrgService;

	/**
	 * 显示所有的部门信息（排序）
	 * 
	 * @param depId
	 * @return
	 */
	public String select() {

		String depId = getRequest().getParameter("depId");
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(getRequest());
		if (StringUtils.isNotEmpty(depId) && !"0".equals(depId)) {
			department = departmentService.get(new Long(depId));
			filters.add(new StringPropertyFilter("LIKES_path", department.getPath()));
		} else {
			List<Department> roots = deptService.findBy("parentId", 0L);
			if (roots.size() > 0) {
				department = roots.get(roots.size() - 1);
				filters.add(new StringPropertyFilter("LIKES_path", department.getPath()));
			}
		}
		
		PageRequest pageReq = ExtjsUtil.getPageReq(getRequest());
		pageReq.setOrderBy("path");
		pageReq.setOrderDir("asc");
		
		Page<Department> page = deptService.search2(pageReq, filters);
		jsonString = new JSON2(page).with(Department.class, "depId", "depName", "depth").toJson();
		return SUCCESS;
	}

	public String treeAll() {
		jsonString = deptService.treeAll();
		return SUCCESS;
	}

	/**
	 * 取得树
	 */
	public String tree() {
		jsonString = deptService.tree();
		return SUCCESS;
	}

	public String list() {
		jsonString = deptService.tree();
		return SUCCESS;
	}

	public String treeByDepth() {
		int depth = Integer.valueOf(getRequest().getParameter("depth"));
		jsonString = deptService.treeByDepth(depth);
		return SUCCESS;
	}

	public String add() {
		Long parentId = department.getParentId();
		String depPath = "";
		int level = 0;
		if (parentId < 1) {
			parentId = new Long(0);
			depPath = "0.";
		} else {
			depPath = departmentService.get(parentId).getPath();
			level = departmentService.get(parentId).getDepth();
		}
		if (level < 1) {
			level = 1;
		}
		department.setDepth(level + 1);
		if (department.getDepId() == null) {
			departmentService.save(department);
		} else {
			department = departmentService.get(department.getDepId());
			try {
				BeanUtil.populateEntity(getRequest(), department, "department");
				departmentService.save(department);
			} catch (Exception e) {
			}
		}
		if (department != null) {
			depPath += department.getDepId().toString() + ".";
			department.setPath(depPath);
			departmentService.save(department);
			setJsonString("{success:true}");
		} else {
			setJsonString("{success:false}");
		}
		return SUCCESS;
	}

	public String remove() {
		PagingBean pb = getInitPagingBean();
		Long depId = Long.parseLong(getRequest().getParameter("depId"));
		Department department = departmentService.get(depId);
		List<AppUser> userList = appUserService.findByDepartment(
				department.getPath(), pb);
		if (userList.size() > 0) {
			setJsonString("{success:false,message:'该部门还有人员，请将人员转移后再删除部门!'}");
			return SUCCESS;
		}
		departmentService.remove(depId);
		List<Department> list = departmentService.findByParentId(depId);
		for (Department dep : list) {
			List<AppUser> users = appUserService.findByDepartment(
					dep.getPath(), pb);
			if (users.size() > 0) {
				setJsonString("{success:false,message:'该部门还有人员，请将人员转移后再删除部门!'}");
				return SUCCESS;
			}
			departmentService.remove(dep.getDepId());
		}
		setJsonString("{success:true}");
		return SUCCESS;
	}

	/**
	 * 新版本删除部门
	 * 
	 * @return
	 */
	public String del() {
		// 删除该部门下的所有部门
		String depId = getRequest().getParameter("depId");
		if (depId != null) {
			departmentService.delCascade(new Long(depId));
		}
		jsonString = "{success:true}";
		return SUCCESS;
	}

	/**
	 * 批量删除
	 */
	public String multiDel() {
		String[] ids = getRequest().getParameterValues("ids");
		try {
			if (ids != null) {
				for (String id : ids) {
					departmentService.delCascade(new Long(id));
				}
			}
			jsonString = "{success:true}";
		} catch (Exception e) {
			e.printStackTrace();
			jsonString = "{success: false, msg: '删除失败，该组织已被使用！'}";
		}
		return SUCCESS;
	}

	/**
	 * 明细
	 */
	public String detail() {
		String orgId = getRequest().getParameter("depId");
		if (StringUtils.isNotEmpty(orgId) && !"0".equals(orgId)) {
			Department dept = deptService.get(new Long(orgId));
			// 主要负责人
			String chargeUser = "";
			try {
				Iterator<UserOrg> auit = dept.getUserOrgs().iterator();
				while (auit.hasNext()) {
					UserOrg uo = auit.next();
					if (uo.getIsCharge() != null && uo.getIsCharge() == 1) {
						chargeUser += uo.getAppUser().getFullname() + ",";
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			if (chargeUser.length() > 0) {
				chargeUser = chargeUser.substring(0, chargeUser.length() - 1);
			}
			getRequest().setAttribute("chargeUser", chargeUser);

			if (dept.getParentId() != null && dept.getParentId() != -1) {
				Department supOrg = deptService.get(dept.getParentId());
				getRequest().setAttribute("supOrg", supOrg);
			}
			getRequest().setAttribute("org", dept);
		}
		return "detail";

	}

	@Deprecated
	public String detail2() {
		Long depId = Long.parseLong(getRequest().getParameter("depId"));
		setDepartment(deptService.get(depId));
		Gson gson = new Gson();
		StringBuffer sb = new StringBuffer("{success:true,data:[");
		sb.append(gson.toJson(department));
		sb.append("]}");
		setJsonString(sb.toString());
		return SUCCESS;
	}

	public String get() {
		Long depId = Long.parseLong(getRequest().getParameter("depId"));
		Department dept = deptService.get(depId);
		jsonString = new JSON(dept).buildWithFilters(2);
		return SUCCESS;
	}

	/**
	 * 添加及保存操作
	 */
	public String save() {
		String chargeIds = getRequest().getParameter("chargeIds");
		if (department.getDepId() == null) {
			// 新增
			department.setCreatetime(new Date());
			department.setUpdatetime(new Date());
			department.setCreatorId(ContextUtil.getCurrentUserId());
			department.setUpdateId(ContextUtil.getCurrentUserId());

			deptService.saveOrUpdate(department);
			Long parentId = department.getParentId();
			if (parentId == 0) {
				department.setPath("0." + department.getDepId() + ".");
				department.setDepth(1);
			} else {
				Department supOrg = deptService.get(parentId);
				department.setPath(supOrg.getPath() + department.getDepId()
						+ ".");
				department.setDepth(supOrg.getDepth() == null ? 1 : supOrg
						.getDepth() + 1);
			}
			deptService.saveOrUpdate(department);

			// 设置分管领导
			if (chargeIds != null && chargeIds.length() > 0) {
				String[] pids = chargeIds.split(",");
				for (int index = 0; index < pids.length; index++) {
					UserOrg userOrg = new UserOrg();
					userOrg.setUserid(new Long(pids[index]));
					userOrg.setOrgId(department.getDepId());
					userOrg.setIsPrimary(new Short("0"));
					userOrg.setIsCharge(new Short("1"));
					userOrgService.save(userOrg);
				}
			}
		} else {
			// 修改
			Department org = deptService.get(department.getDepId());
			try {
				Long parentId = org.getParentId();
				if (parentId == 0) {
					org.setPath("0." + department.getDepId() + ".");
					org.setDepth(1);
				} else {
					Department supOrg = deptService.get(parentId);
					org.setPath(supOrg.getPath() + org.getDepId() + ".");
					org.setDepth(supOrg.getDepth() + 1);
				}
				org.setUpdatetime(new Date());
				org.setUpdateId(ContextUtil.getCurrentUserId());
				BeanUtil.copyNotNullProperties(org, department);
				deptService.saveOrUpdate(org);

				// 1、获得当前组织的分管领导
				String hql = "from UserOrg where isPrimary=0 and isCharge=1 and dept=?";
				List<UserOrg> list = userOrgService.getByHql(hql, org);
				for (UserOrg uo : list) {
					userOrgService.remove(uo);
				}
				if (chargeIds != null && chargeIds.length() > 0) {
					String[] pids = chargeIds.split(",");
					for (int index = 0; index < pids.length; index++) {
						UserOrg userOrg = new UserOrg();
						userOrg.setUserid(new Long(pids[index]));
						userOrg.setOrgId(department.getDepId());
						userOrg.setIsPrimary(new Short("0"));
						userOrg.setIsCharge(new Short("1"));
						userOrgService.save(userOrg);
					}
				}
			} catch (Exception ex) {
				logger.error(ex.getMessage());
			}
		}
		setJsonString("{success:true}");
		return SUCCESS;
	}

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

}
